package com.mi.cmdtest;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.magilit.framelibrary.annotations.ViewInject;
import com.magilit.framelibrary.base.FrameNormalActivity;
import com.mi.cmdlibrary.magilit.callback.OnMagilitDataListener;
import com.mi.cmdlibrary.magilit.cmdpacket.receive.ReceiveRealPacket;
import com.mi.cmdlibrary.magilit.cmdpacket.receive.ReceiveSixRealPacket;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * SKD 测试工具
 * Created by lewis on 2017/12/8.
 */

public class TestActivity extends FrameNormalActivity implements View.OnClickListener {
    @ViewInject(R.id.bt_send_key)
    Button bt_send_key;

    @ViewInject(R.id.bt_query_electric)
    Button bt_query_electric;

    @ViewInject(R.id.bt_query_serial_number)
    Button bt_query_serial_number;
    @ViewInject(R.id.bt_query_app_version)
    Button bt_query_app_version;
    @ViewInject(R.id.bt_query_ble_version)
    Button bt_query_ble_version;
    @ViewInject(R.id.bt_unbound)
    Button bt_unbound;


    @ViewInject(R.id.tv_send)
    private TextView tv_send;

    @ViewInject(R.id.clear_receive)
    private TextView clear_receive;

    @ViewInject(R.id.bt_close_real)
    private Button bt_close_real;
    @ViewInject(R.id.bt_close_real_six)
    private Button bt_close_real_six;
    @ViewInject(R.id.bt_open_real)
    private Button bt_open_real;

    @ViewInject(R.id.bt_open_real_six)
    private Button bt_open_real_six;

    @ViewInject(R.id.bt_connect)
    private Button bt_connect;
    @ViewInject(R.id.bt_open_auto_query)
    private Button bt_open_auto_query;


    @ViewInject(R.id.bt_close_auto_query)
    private Button bt_close_auto_query;




    @ViewInject(R.id.bt_choose_file)
    private Button bt_choose_file;

    @ViewInject(R.id.bt_update)
    private Button bt_update;
    @ViewInject(R.id.bt_send_file)
    private Button bt_send_file;



    @ViewInject(R.id.lv_receive)
    private ListView lv_receive;
    private ArrayAdapter adapter;
    private List<String> data_receive = new ArrayList<>();


    @Override
    protected void onBaseActivityCreated(Bundle savedInstanceState) {
        setMyContentView(R.layout.activity_test);
        adapter = new ArrayAdapter(this, R.layout.item_receive_data, data_receive);
        lv_receive.setAdapter(adapter);

        bt_update.setOnClickListener(this);
        bt_send_file.setOnClickListener(this);
        bt_choose_file.setOnClickListener(this);
        clear_receive.setOnClickListener(this);
        bt_send_key.setOnClickListener(this);

        bt_query_electric.setOnClickListener(this);

        bt_query_serial_number.setOnClickListener(this);
        bt_query_app_version.setOnClickListener(this);
        bt_query_ble_version.setOnClickListener(this);
        bt_unbound.setOnClickListener(this);

        bt_close_real_six.setOnClickListener(this);
        bt_close_real.setOnClickListener(this);
        bt_open_real_six.setOnClickListener(this);
        bt_open_real.setOnClickListener(this);



        bt_connect.setOnClickListener(this);
        bt_close_auto_query.setOnClickListener(this);
        bt_open_auto_query.setOnClickListener(this);


        TestApplication.getInstance().getBt1().addOnMagilitDataListener(new OnMagilitDataListener() {

            @Override
            public void onRealReceive(String tag, ReceiveRealPacket packet) {
                showText(ArrayUtils.backCMD2String(packet.getData()));
            }

            @Override
            public void onSixRealReceive(String tag, ReceiveSixRealPacket packet) {
                showText(ArrayUtils.backCMD2String(packet.getData()));
            }

            @Override
            public void onElectricReceive(String tag, int electric) {
                showText("电量:  " + electric);
            }


            @Override
            public void onSerialNumberReceive(String tag, String serialNumber) {
                showText("序列号:  " + serialNumber);
            }

            @Override
            public void onFirmVersionReceive(String tag, String firmVersion) {
                showText("固件版本号:  " + firmVersion);
            }

            @Override
            public void onBleVersionReceive(String tag, String bleVersion) {
                showText("蓝牙版本号:  " + bleVersion);
            }
        });

//        new BtDeviceBuilder().timeout(10000).matcher(new BTDeviceMatcher(mac)).build(new BtDeviceBuilder.OnDeviceSearchListener() {
//            @Override
//            public void onDeviceSearch(BluetoothDevice device) {
//                TestApplication.getInstance().getBt1().setBluetoothDevice(device);
//                TestApplication.getInstance().getBt1().connect();
//            }
//
//            @Override
//            public void onTimeOut() {
//
//            }
//        });
    }


    @Override
    protected boolean showToolBar() {
        return false;
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.bt_send_key:

                break;
            case R.id.bt_query_electric:
                TestApplication.getInstance().getBt1().queryElectric();
                break;
            case R.id.bt_query_serial_number:
                TestApplication.getInstance().getBt1().querySerialNumber();
                break;
            case R.id.bt_query_app_version:
                TestApplication.getInstance().getBt1().queryFirmVersion();
                break;
            case R.id.bt_query_ble_version:
                TestApplication.getInstance().getBt1().queryBleVersion();
                break;
            case R.id.bt_open_real_six:
                TestApplication.getInstance().getBt1().openSixReal();
                break;
            case R.id.bt_open_real:
                TestApplication.getInstance().getBt1().openReal();
                break;
            case R.id.bt_close_real_six:
                TestApplication.getInstance().getBt1().closeSixReal();
                break;
            case R.id.bt_close_real:
                TestApplication.getInstance().getBt1().closeReal();
                break;
            case R.id.clear_receive:
                data_receive.clear();
                adapter.notifyDataSetChanged();
                break;
            case R.id.bt_connect:
                startActivity(new Intent(this, SearchDeviceActivity.class));
                break;
            case R.id.bt_close_auto_query:
                break;
            case R.id.bt_open_auto_query:
                break;

            case R.id.bt_choose_file:
                chooseFile();
                break;
            case R.id.bt_update:
                TestApplication.getInstance().getBt1().updateFirm();
                TestApplication.getInstance().getBt1().getState().setOnUpdating(true);
                break;
            case R.id.bt_send_file:
                updateHelper = new UpdateHelper(TestApplication.getInstance().getBt1(), data_file, myFilePath.getName());
                updateHelper.startFirmUpgrade();
                break;
        }
    }

    private void showText(final String text) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                data_receive.add(text);
                adapter.notifyDataSetChanged();
                lv_receive.setSelection(adapter.getCount() - 1);
            }
        });
    }

    private void sendMuch() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 5; i++) {
                    TestApplication.getInstance().getBt1().queryElectric();
                    SystemClock.sleep(100);
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 5; i++) {
                    TestApplication.getInstance().getBt1().queryFirmVersion();
                    SystemClock.sleep(100);
                }
            }
        }).start();
        for (int i = 0; i < 5; i++) {
            TestApplication.getInstance().getBt1().queryState();
        }

    }


    private static final int CHOOSE_FILE = 0x11;

    private void chooseFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");//无类型限制
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, CHOOSE_FILE);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == CHOOSE_FILE) {
            if (resultCode == Activity.RESULT_OK) {
                Uri uri = intent.getData();
                myFilePath = new File(uri.getPath());
                init();

            }
        }
    }

    private UpdateHelper updateHelper;
    private byte[] data_file;
    private long file_len;
    private File myFilePath;

    /**
     * 初始化
     * 图片路径
     */
    public void init() {
        int len;
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(myFilePath);
            file_len = myFilePath.length();

            ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
            byte[] read = new byte[1024];
            while ((len = inputStream.read(read)) != -1) {
                bos.write(read, 0, len);
            }
            byte[] bytes = bos.toByteArray();

            if (bytes.length % 128 != 0) {
                data_file = ArrayUtils.concatAll(bytes, new byte[128 - bytes.length % 128]);
            } else {
                data_file = bytes;
            }

        } catch (FileNotFoundException e) {
            Toast.makeText(this, "找不到指定文件", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
